package xing.infrastructure.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

/********************************
 * 文 件 名 :Aes.java
 * 创 建 人：陈天龙
 * 日    期：2017/10/16
 * 描   述：AES解密
 * 版 本 号：v1.0.0
 ********************************/
public class Aes {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static boolean initialized = false;

    public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (NoSuchAlgorithmException e) {
            logger.error("解密错误",e);
        } catch (NoSuchPaddingException e) {
            logger.error("解密错误",e);
        } catch (InvalidKeyException e) {
            logger.error("解密错误",e);
        } catch (IllegalBlockSizeException e) {
            logger.error("解密错误",e);
        } catch (BadPaddingException e) {
            logger.error("解密错误",e);
        } catch (NoSuchProviderException e) {
            logger.error("解密错误",e);
        } catch (Exception e) {
            logger.error("解密错误",e);
        }
        return null;
    }

    public static void initialize(){
        if (initialized) return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }
}
